package controladores;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import modelo.Persona;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import services.PersonaService;
import validadores.ValidadorPersona;

@Controller
@RequestMapping("/nuevaPersona")
public class ControladorPersona {
	@Autowired
	private PersonaService personas;
	
	@RequestMapping(method = RequestMethod.GET)
	public String setUpForm(ModelMap model){
		return "accionPersona";
	}
	
	@ModelAttribute(value="sexo")
	public Map<String, String> sexo(){
		Map<String, String> sexo = new HashMap<String, String>();
		sexo.put("Masculino", "M");
		sexo.put("Femenino", "F");
		return sexo;
	}
	
	@ModelAttribute(value="localidades")
	public List<String> localidades(){
		return Arrays.asList("Avellaneda", "Quilmes", "Capital Federal", "Otro");
	}
	
	@ModelAttribute(value="persona")
	public Persona persona(){
		return new Persona();
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String postear(Persona persona, BindingResult errors){
		new ValidadorPersona().validate(persona, errors);
		if (errors.hasErrors())
			return "accionPersona";
		personas.agregarPersona(persona);
		return "redirect:personas";
	}
}